<template>
  <NotLogged v-if="!store.$state.token" />
  <view v-else class="w-screen gradient-background" :style="{ height: `calc(100vh - ${store.$state.tabbarHeight}px)` }">
    <view :style="{ paddingTop: `${headerHeight}px` }" class="c-pd">
      <view id="equipIndexUnScroll">
        <view class="flex justify-left items-center pt-[10px]">
          <view class="text-[18px] font-bold c-text-ellipsis w-fit" style="max-width: calc(100% - 73px)">{{ state.localeName }}</view>
          <i class="i-ic:baseline-arrow-drop-down color-black text-40px" @click="findLocaleOptions.show = true"></i>
        </view>

        <view>
          <view class="c-text-12">{{ state.equipList.length }}个设备</view>
          <view class="flex justify-between items-center mt-[30px]">
            <view class="flex">
              <view class="c-text-16">设备</view>
              <navigator class="flex flex-1 flex-wrap justify-center px-20px" :url="'/subcontract/equipment/locale/detail/index?id=' + state.localeId">
                <view class="w-[100%] text-center c-text-16"> 场所 </view>
              </navigator>
              <navigator class="flex flex-1 flex-wrap justify-center" url="/subcontract/equipment/locale/index">
                <view class="w-[100%] text-center c-text-16"> 所有 </view>
              </navigator>
            </view>

            <view>
              <van-icon name="plus" color="black" size="55rpx" @click="toScan" />
              <van-icon name="replay" color="black" size="55rpx" @click="getEquipList" style="margin-left: 30rpx" />
            </view>
          </view>
        </view>
      </view>

      <view v-if="state.equipList.length > 0 && state.localeState" class="grid grid-cols-2 gap-x-12px overflow-y-scroll mt-20px" :style="{ maxHeight: `calc(100vh - 20px - ${state.contentHeight}px)` }">
        <view v-for="(item, index) in state.equipList" @click="gotoEquipDetails(item.id)" :key="index">
          <view class="c-br flex flex-col px-6px mb-12px box-border c-pd" :style="{ backgroundColor: `${formatEquipBgColor(item.state, item.errorState, item.powerState)}` }">
            <view class="flex justify-between">
              <van-image round width="80px" height="80px" fit="cover" :src="EEquipLogo[item.type]" />
              <van-button plain hairline round type="primary" size="small" v-if="item.type === 1 && item.beeperType === 2" @click="gotoRecharge">充值</van-button>
            </view>
            <view class="c-text-14 font-bold mt-[6px] pl-4px" :style="{ color: `${formatEquipTextColor(item.state, item.errorState, item.powerState)}` }">{{ item.name }}</view>
            <view class="flex justify-left items-center c-text-12 mt-[4px] pl-4px" :style="{ color: `${formatEquipTextColor(item.state, item.errorState, item.powerState)}` }">
              <text>{{ formatEquipState(item.state, item.errorState, item.powerState) }} </text>
              <text v-if="item.installArea">&nbsp| {{ item.installArea }}</text>
            </view>
          </view>
        </view>
      </view>
      <van-empty v-if="state.equipList.length === 0 && state.localeState" description="暂无呼叫器设备，快去点击右上的+号扫码添加" />
      <van-empty v-if="!state.localeState" description="该场所正在审核，请耐心等待" />
    </view>

    <van-popup :show="findLocaleOptions.show" round position="bottom" @close="findLocaleOptions.show = false">
      <view class="bg-white">
        <van-search shape="round" placeholder="请输入搜索关键词" @change="(e: any) => (findLocaleOptions.searchText = e.detail)" />
        <view class="min-h-[20vh] max-h-[50vh] c-pd">
          <view v-for="item in state.localeList" :key="item.id" @click="handleChangeLocale(item.id)">
            <view class="flex justify-between items-center">
              <view>
                <text v-if="item.mainFlag" class="color-blue text-[16px] font-bold"> (主) </text>
                <text class="text-[16px]" :class="item.id === state.localeId ? 'c-color-sec' : ''">{{ item.name }}</text>
                <i v-if="!item.state" class="i-proicons:do-not-disturb text-30px c-text-color-grey">></i>
              </view>
              <view>
                <i v-if="item.id === state.localeId" class="i-ep:select c-color-sec" />
              </view>
            </view>
            <van-divider />
          </view>
        </view>
      </view>
    </van-popup>
  </view>

  <TabBar active-tab="设备" />
</template>

<script setup lang="ts">
import { useAppStore } from '@/store';
import EquipRequest from '@/request/equipRequest';
import { EEquipLogo } from '@/enum/equip';
import EquipTool from '@/utils/equipTool';
import { navigate } from '@/utils/navigate';
import { useSelectorQuery } from '@/hooks/useSelectorQuery';
import eventBus from '@/utils/eventBus';
interface IState {
  localeId: number;
  localeName: string;
  localeState: number;
  localeList: ILocaleFewInfoRes[];
  equipList: IEquipRes[];
  contentHeight: number;
}

const store = useAppStore();
const state = reactive<IState>({ localeId: 0, localeName: '', localeState: 0, localeList: [], equipList: [], contentHeight: 0 });
const { beeperId, headerHeight, tabbarHeight } = store.$state;
const findLocaleOptions = reactive({
  show: false,
  searchText: '',
});

onLoad(() => {
  if (!useAppStore().$state.token) return;
  getLocaleList();
  getEquipIndexUnScrollHeight();
  eventBus.on('callAlarmNotification', getLocaleList);
});

onUnmounted(() => {
  eventBus.off('callAlarmNotification');
});

watch(
  () => beeperId,
  (value) => {
    if (value > 0) {
      getLocaleList();
    }
  },
);

// 计算设备列表高度
const getEquipIndexUnScrollHeight = () => {
  useSelectorQuery('#equipIndexUnScroll', null).then((res) => {
    state.contentHeight += res.height!;
    state.contentHeight += headerHeight;
    state.contentHeight += tabbarHeight;
  });
};

// 获取用户的场所列表
const getLocaleList = () => {
  EquipRequest.LocaleList({ containBeeper: 1, hasLoading: true }).then((res) => {
    state.localeList = res.data;
    if (res.data.length === 0) {
      return;
    }
    if (beeperId > 0) {
      state.localeId = EquipTool.currentLocaleId(res.data, beeperId);
      res.data.find((item) => {
        if (item.id == state.localeId) {
          state.localeName = item.name;
          state.localeState = item.state;
        }
      });
    } else {
      state.localeId = state.localeList[0].id;
      state.localeName = state.localeList[0].name;
      state.localeState = state.localeList[0].state;
    }
    getEquipList();
  });
};

// 获取场所的设备列表
const getEquipList = () => {
  if (state.localeId > 0) {
    EquipRequest.LocaleEquipList({ localeId: state.localeId, hasLoading: true }).then((res) => {
      state.equipList = res.data;
    });
  }
};

// 场所切换
const handleChangeLocale = (id: number) => {
  findLocaleOptions.show = false;
  state.localeId = id;
  let chooseLocale = state.localeList.find((item) => item.id == id);
  if (chooseLocale) {
    state.localeName = chooseLocale.name;
  }
  getEquipList();
};

// state:0.未开通 1.待连接 2.在线 3.离线  errorState:0:正常 1:报警 powerState:0.禁用 1.启用
const formatEquipState = (state: number, errorState: number, powerState: number) => {
  if (powerState === 0) return '禁用';
  if (errorState === 1) return '报警';
  if (state === 2) return '在线';
  else return '离线';
};
const formatEquipBgColor = (state: number, errorState: number, powerState: number) => {
  if (powerState === 0) return 'rgba(255, 255, 255, 0.8)';
  if (errorState === 1) return 'rgba(245, 114, 114, 0.8)';
  if (state === 2) return 'rgba(106, 202, 106, 0.8)';
  else return 'rgba(255, 255, 255, 0.8)';
};
const formatEquipTextColor = (state: number, errorState: number, powerState: number) => {
  if (powerState === 0) return 'black';
  if (errorState === 1) return 'white';
  if (state === 2) return 'white';
  else return 'black';
};

// 扫码绑定设备
const toScan = () => {
  wx.scanCode({
    success: (res) => {
      //扫描后示例：pages/index/bindingEquipment/index?scene=ec=SL10000001
      const arr = res.path.split('scene=');
      const path = `${arr[0]}scene=${encodeURIComponent(arr[1])}&localeId=${state.localeId}`;
      navigate({ url: '/' + path });
    },
  });
};
// 跳转设备详情页
const gotoEquipDetails = (equipId: number) => {
  // 非主用户无法进入公共呼叫器详情页，提示：非主用户无权限进入

  navigate({ url: '/subcontract/equipment/equipDetail/index?id=' + equipId });
};

// 呼叫器余额充值
const gotoRecharge = () => {};
</script>

<style>
.gradient-background {
  background-size: 100% 100%;
  background-image: linear-gradient(to bottom, #d7dde9, #fff);
}
</style>
